package cn.edu.scau.jds.dao;

import cn.edu.scau.jds.entity.Course;
import cn.edu.scau.jds.entity.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * Created by junbin(seraphstorm@163.com) on 2016-01-26.
 */
@Repository(value = "userDao")
public class UserDao extends BaseDao<User> {

    public void deleteUserJob(long id) {
        this.getSqlSession().delete(getMethodPath("deleteUserJob"), id);
    }

    public void deleteUserCourse(long id) {
        this.getSqlSession().delete(getMethodPath("deleteUserCourse"), id);
    }

    public void deleteUser(long id) {
        this.getSqlSession().update(getMethodPath("deleteUser"), id);
    }

    public void updatePassword(User user) {
        this.getSqlSession().update(getMethodPath("updateUserPassword"), user);
    }

    public void updateQq(User user) {
        this.getSqlSession().update(getMethodPath("updateUserQq"), user);
    }

    public User loadBySid(String sid) {
        return this.getSqlSession().selectOne(getMethodPath("loadBySid"), sid);
    }

    public User aggressiveLoad(long id) {
        return this.getSqlSession().selectOne(getMethodPath("aggressiveLoad"), id);
    }

    public void addCourse(User user, Course course) {
        Map<String, Long> map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("courseId", course.getId());
        this.getSqlSession().update(getMethodPath("addCourse"), map);
        user.getCourseList().add(course);
    }

    public void deleteCourse(User user, Course course) {
        Map<String, Long> map = new HashMap<>();
        map.put("userId", user.getId());
        map.put("courseId", course.getId());
        this.getSqlSession().update(getMethodPath("deleteCourse"), map);
        CopyOnWriteArrayList<Course> courseList = user.getCourseList().stream()
                .collect(Collectors.toCollection(CopyOnWriteArrayList::new));
        courseList.stream().filter(c -> c.getId() == course.getId()).forEach(courseList::remove);
        user.setCourseList(courseList.stream().collect(Collectors.toList()));
    }

}
